<template>
  <el-col class="operate-fields" :class="[isAdd? '': 'edit-backgr']">
    <div class="title">{{addTitle}}</div>
    <el-form :model="customizeFieldData"  :label-position="labelPosit" ref="customizeFieldData" :rules="rules" label-width="100px">
      <el-col>
        <el-form-item :label="$t('config.customer.fieldName')" prop="name">
          <el-input v-model.trim="customizeFieldData.name" size="mini" style="width: 195px" :maxlength="35"></el-input>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item :label="$t('config.customer.whetherNecessary')">
          <el-radio-group v-model="customizeFieldData.required">
            <el-radio class="radio" label="required">{{$t('public.yes')}}</el-radio>
            <el-radio class="radio" label="norequire">{{$t('public.no')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item :label="$t('public.changeLog')">
          <el-radio-group v-model="customizeFieldData.saveLog">
            <el-radio class="radio" :label="true">{{$t('public.yes')}}</el-radio>
            <el-radio class="radio" :label="false">{{$t('public.no')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col>
        <el-form-item :label="$t('config.customer.noupdate')">
          <el-radio-group v-model="customizeFieldData.noupdate">
            <el-radio class="radio" :label="true">{{$t('public.yes')}}</el-radio>
            <el-radio class="radio" :label="false">{{$t('public.no')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <custom-fields-type :isAdd="isAdd" :formdata = "formdata" :isRequire="customizeFieldData.required" @customizeFieldType="handleCustomizeFieldType"></custom-fields-type>
    </el-form>
    <el-col class="footer">
      <el-button @click.stop="cannelCustomizeField" class='primary_btn'>{{$t('public.cancel')}}</el-button>
      <el-button type="primary" @click.stop="saveCustomizeField" class='primary_btn'>{{$t('public.confirm')}}</el-button>
    </el-col>
  </el-col>
</template>
<script>
  import CustomFieldsType from './CustomFieldsType.vue'
  import { deepClone, labelPosition } from '@/utils/m7Utils.js'
  export default {
    name: 'OperateCustomField',
    data () {
      return {
        labelPosit: labelPosition,
        rules: {
          name: [
            {required: true, message: this.$t('validate.required'), trigger: 'blur'}
          ]
        },
        customizeRequire: 'required',
        customizeFieldData: {},
        formdata: {
          formdataChoices: [],
          mustFill: '',
          dic: {
            dicId: '',
            isDic: false
          },
          type: ''
        }
      }
    },
    props: {
      addTitle: String,
      isAdd: Boolean,
      template_id: String,
      customizeField: {
        type: Object,
        default: function () {
          return {
            saveLog: false,
            status: 'run',
            name: '',
            required: 'required',
            noupdate: true,
            type: 'single',
            choices: ['']
          }
        }
      },
      email: {
        type: Object,
        default: function () {
          return {
            isShow: true,
            lastCodeKey: ''
          }
        }
      }
    },
    methods: {
      cannelCustomizeField () {
        this.$emit('customizeFields', {data: this.customizeFieldData, flag: false, isAdd: this.isAdd})
      },
      handleCustomizeFieldType (data) {
        this.formdata.type = data.type
      },
      saveEditCustomize () {
        this.$refs.customizeFieldData.validate((valid) => {
          if (valid) {
            let data
            if (this.formdata.type === 'dropdown' || this.formdata.type === 'checkbox' || this.formdata.type === 'radio') {
              // 编辑为对象 添加为数组
              let choices = {0: ''}
              for (let i = 0; i < this.formdata.formdataChoices.length; i++) {
                if (this.formdata.formdataChoices[i]) {
                  choices[this.formdata.formdataChoices[i].key] = this.formdata.formdataChoices[i].value
                }
              }
              data = {
                status: this.customizeFieldData.status || 'run',
                saveLog: this.customizeFieldData.saveLog,
                _id: this.customizeFieldData._id,
                template_id: this.template_id,
                type: this.formdata.type,
                choices: choices,
                name: this.customizeFieldData.name,
                required: this.customizeFieldData.required === 'required' ? 'required' : '',
                noupdate: this.customizeFieldData.noupdate
              }
              let dic = this.formdata.dic
              if (dic && dic.isDic) {
                data.dic = {
                  isDic: dic.isDic,
                  dicId: dic.dicId
                }
                if (data.required) {
                  if (this.formdata.mustFill === '') {
                    this.$message.error(this.$t('configLazyLoad.customerConfig.errorTip9'))
                    return
                  }
                  data.mustFill = this.formdata.mustFill
                } else {
                  data.mustFill = ''
                }
                if (this.formdata.type !== 'dropdown') {
                  delete data.dic
                }
              }
            } else {
              data = {
                status: this.customizeFieldData.status || 'run',
                saveLog: this.customizeFieldData.saveLog,
                _id: this.customizeFieldData._id,
                template_id: this.template_id,
                type: this.formdata.type,
                name: this.customizeFieldData.name,
                required: this.customizeFieldData.required === 'required' ? 'required' : '',
                noupdate: this.customizeFieldData.noupdate
              }
            }
            this.$store.dispatch('editCustomField', data).then(resp => {
              if (resp.success) {
                this.$message.success(this.$t('userInfo.editSuccess'))
                data.flag = false
                this.$emit('customizeFieldsSuccess', {data: data, flag: false, isAdd: false})
              } else {
                this.$message.error(this.$t('userInfo.editFail'))
              }
            })
          }
        })
      },
      saveAddCustomize () {
        this.$refs.customizeFieldData.validate((valid) => {
          if (valid) {
            let data
            if (this.formdata.type === 'dropdown' || this.formdata.type === 'checkbox' || this.formdata.type === 'radio') {
              let choices = []
              for (let i = 0; i < this.formdata.formdataChoices.length; i++) {
                if (this.formdata.formdataChoices[i]) {
                  choices.push(this.formdata.formdataChoices[i].value)
                }
              }
              choices = choices.length === 0 ? [''] : choices
              data = {
                status: 'run',
                saveLog: this.customizeFieldData.saveLog,
                template: this.template_id,
                type: this.formdata.type,
                choices: choices,
                name: this.customizeFieldData.name,
                required: this.customizeFieldData.required === 'required' ? 'required' : '',
                noupdate: this.customizeFieldData.noupdate
              }
              let dic = this.formdata.dic
              if (dic.isDic) {
                data.dic = {
                  isDic: dic.isDic,
                  dicId: dic.dicId
                }
                if (data.required) {
                  if (this.formdata.mustFill === '') {
                    this.$message.error(this.$t('configLazyLoad.customerConfig.errorTip9'))
                    return
                  }
                  data.mustFill = this.formdata.mustFill
                } else {
                  data.mustFill = ''
                }
                if (this.formdata.type !== 'dropdown') {
                  delete data.dic
                }
              }
            } else {
              data = {
                status: 'run',
                saveLog: this.customizeFieldData.saveLog,
                template: this.template_id,
                type: this.formdata.type,
                name: this.customizeFieldData.name,
                required: this.customizeFieldData.required === 'required' ? 'required' : '',
                noupdate: this.customizeFieldData.noupdate
              }
            }
            this.$store.dispatch('addCustomerField', data).then(resp => {
              if (resp.success) {
                this.$message.success(this.$t('config.customer.addSucc'))
                data.flag = false
                data._id = resp._id
                this.$emit('customizeFieldsSuccess', {data: data, flag: false, isAdd: true})
              } else {
                this.$message.error(this.$t('call.addLabelFail'))
              }
            })
          }
        })
      },
      saveCustomizeField () {
        if (this.isAdd) {
          this.saveAddCustomize()
        } else {
          this.saveEditCustomize()
        }
      }
    },
    components: {
      CustomFieldsType
    },
    beforeMount () {
      this.customizeFieldData = deepClone(this.customizeField)
      if (this.customizeFieldData.required === '') {
        this.customizeFieldData.required = 'norequire'
      } else {
        this.customizeFieldData.required = 'required'
      }
      if (this.customizeFieldData.saveLog) {
        this.$set(this.customizeFieldData, 'saveLog', true)
      } else {
        this.$set(this.customizeFieldData, 'saveLog', false)
      }
      for (let key in this.customizeFieldData.choices) {
        this.formdata.formdataChoices.push({key: key, value: this.customizeFieldData.choices[key]})
      }
      if (this.customizeFieldData.dic) {
        this.formdata.dic = {...this.customizeFieldData.dic}
        if (this.formdata.dic.isDic) {
          this.formdata.mustFill = this.customizeFieldData.mustFill || 'all'
        } else {
          this.formdata.mustFill = ''
        }
      }
      this.formdata.type = this.customizeFieldData.type
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .edit-backgr
    background-color #f0f0f0
    margin 10px 0px
  .operate-fields
    width: 478px
    padding-left 10px
    margin-bottom 20px
    .title
      font-size 14px
      font-weight 500
      padding 10px 0px
    .footer
      padding 10px 0px 10px 80px
  .email-resend__btn
    display block
    margin-top 10px
</style>
